package com.qq.BFMRSE.index;

import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.qq.BFMRSE.extractWord.SelectWord;
import com.qq.BFMRSE.extractWord.wordTFAndIDFInfo;
import com.qq.BFMRSE.serialize.objectSerializeUtil;
import com.qq.BFMRSE.util.BFConstants;
import com.qq.BFMRSE.util.UserParamManager;


public class indexHelper {
	public  static List<String> wordList;
	public  static SelectWord selectWord;
	static{
		wordList=wordTFAndIDFInfo.getAllDistinctWord();
		try {
			selectWord=(SelectWord) objectSerializeUtil.deserialize(BFConstants.WORDINFOFILE+File.separator+BFConstants.INITKEYVALUE);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public static void update()
	{
		wordList=wordTFAndIDFInfo.getAllDistinctWord();//更新
	}
	/**
	 * 得到文件fileName的明文索引
	 * @param fileName
	 * @param n
	 * @return
	 */
	public static double [] getSearchPlainIndex(String fileName)
	{
		update();
		//int disWordCont=wordList.size();
		//System.out.println("test disWordCont="+wordList.size());
		int u=BFConstants.U;//u为dummuy keyword的个数
		double c=Math.sqrt(3.0/(u/2))*0.01;
		//int n=disWordCont+BFConstants.DUMMUYKWYWORDCOUNT;//100个空位置中前2v个作为dummuy keyword,后80作为用于更新时使用
		//int n=selectWord.getN();
		int n=UserParamManager.getVectorLength();
		int disWordCont=UserParamManager.getDistintWordCount();
		System.out.println("test getSearchPlainIndex n="+n);
		double []resultIndex=new double[n];
		for(int i=0;i<n;i++)
		{
			resultIndex[i]=0;
		}
		Map<String, Double> wordTFMap=wordTFAndIDFInfo.getWordAndIdfsByFileName(fileName);
		double tfsNorm=getNorValues(wordTFMap);
		Set<String> wordSet=wordTFMap.keySet();
		Iterator<String> iterator=wordSet.iterator();
		while(iterator.hasNext())
		{
			String tempWord=iterator.next();
			int index=wordList.indexOf(tempWord);
			resultIndex[index]=wordTFMap.get(tempWord)/tfsNorm;
		}
		for(int i=disWordCont;i<n;i++)
		{
			resultIndex[i]=indexBuildTool.getUniformRandom(c);
		}
		return resultIndex;
	}
	public static double getNorValues(Map<String, Double> wordTFMap)
	{
		double tfNors=0;
		Set<String> wordSet=wordTFMap.keySet();
		Iterator<String> iterator=wordSet.iterator();
		while(iterator.hasNext())
		{
			String tempWord=iterator.next();
			tfNors+=Math.pow(wordTFMap.get(tempWord),2);
		}
		tfNors=Math.sqrt(tfNors);
		return tfNors;
	}

}
